package com.example.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HttpUtil {

    private final static CloseableHttpClient CLIENT = HttpClients.createDefault();

    /**
     * @description: 发送GET请求
     *
     * @param host 请求地址
     * @param port 端口号
     * @param: requestUrl
     * @return: org.apache.http.client.methods.CloseableHttpResponse
     */
    public static CloseableHttpResponse sendGet(String host, int port, String uri) throws Exception{
        HttpGet httpGet = new HttpGet("http:" + getURI(host, port, uri));
        httpGet.addHeader("Cookie", " jsessionid=DZK99999999_API_TEST");
        return CLIENT.execute(httpGet);
    }

    /**
     * @description: 生成请求URI
     *
     * @param host 请求地址
     * @param port 端口号
     * @param: uri
     * @return: java.net.URI
     */
    private static URI getURI(String host, int port, String uri) throws Exception{
        URIBuilder uriBuilder = new URIBuilder();
        String path = uri.substring(0, uri.indexOf("?"));
        String[] params = uri.substring(uri.indexOf("?")+1).split("&");

        uriBuilder.setCharset(Charset.forName("UTF-8"));
        uriBuilder.setHost(host);
        uriBuilder.setPort(port);
        uriBuilder.setPath(path);

        for (int i = 0; i < params.length; i++) {
            String[] kv = params[i].split("=");
            uriBuilder.setParameter(kv[0], kv.length == 2 ? kv[1] : null);
        }
        return uriBuilder.build();
    }

    /**
     * @description: 解析responseEntity
     *
     * @param: is
     * @return: java.lang.String
     */
    public static String readResponseEntity(HttpEntity httpEntity) throws IOException {
        InputStream is = httpEntity.getContent();
        if (is == null) {
            return null;
        }

        StringBuilder str = new StringBuilder();

        try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is))) {
            while (true) {
                String readLine = bufferedReader.readLine();
                if (readLine == null) {
                    break;
                }
                str.append(readLine);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            is.close();
        }

        return parseMap(str.toString());
    }

    private static String parseMap(String jsonString) {
        StringBuilder message = new StringBuilder();
        try {
            Map<String, Object> resultEntity = JSONObject.parseObject(jsonString, HashMap.class);

            message.append("{");

            if (resultEntity != null && !resultEntity.isEmpty()) {
                message.append("\n");
                for (Map.Entry<String, Object> entry : resultEntity.entrySet()) {
                    message.append("\t").append(entry.getKey()).append(": ").append(entry.getValue()).append(",").append("\n");
                }
                message.replace(message.lastIndexOf(","), message.lastIndexOf(",") + 1, "");
            }
            message.append("}");
        } catch (RuntimeException e) {
            throw new RuntimeException("字符串转JSON转换失败", e);
        }
        return message.toString();
    }
}
